package com.zxp.zxpsmarthomeapk.communicate;

import android.os.Handler;
import android.os.Message;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by zhangxianpeng on 2018/4/2.
 * 接收模块发送过来的消息的服务器
 */

public class CommunicateServer implements Runnable {
    private ServerSocket serverSocket;
    private DataInputStream inputStream;
    private byte[] receive;
    private Handler handler = new Handler();

    public CommunicateServer() {
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    /**
     * 5000是手机端开启的服务器的端口号，ESP8266进行TCP连接时使用的端口，而IP也是通过指令查询的联入设备的IP
     */
    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(5000);
            while (true) {
                Socket client = serverSocket.accept();
                inputStream = new DataInputStream(client.getInputStream());
                receive = new byte[50];
                inputStream.read(receive);
                inputStream.close();

                Message msg = new Message();
                msg.what = 1;
                msg.obj = new String(receive);
                handler.sendMessage(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (serverSocket != null) {
                serverSocket.close();
            } else {
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
